package ass.web;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ass.beans.UserBean;
import ass.beans.UserFriendsBean;
import ass.dao.UserDAO;
import ass.dao.UserFriendsDAO;
import ass.dao.support.UserDAOImpl;
import ass.dao.support.UserFriendsDAOImpl;
import ass.util.Mail;

/**
 * Servlet implementation class SubmitFriendRequest
 */
public class SubmitFriendRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SubmitFriendRequest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute("username");
		
		String usernameFriend = (String) request.getParameter("username");
		String message = (String) request.getParameter("message");
		
		
		UserFriendsDAO userFriendsDAO = new UserFriendsDAOImpl();
		UserFriendsBean userFriendsBean = new UserFriendsBean();
		
		UserDAO  userDAO = new UserDAOImpl();
		UserBean userNewFriendBean = userDAO.getUser(usernameFriend);
		UserBean userBean = userDAO.getUser(username);
		
		userFriendsBean.setUsernameFriend(usernameFriend);
		userFriendsBean.setUsername(username);
		userFriendsBean.setMessage(message);
		
		String nextJSP = "";
		nextJSP = "/userFrdSearchDetail.jsp?username="+usernameFriend;
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
		
		String[] a = new String[1];
		a[0] = userNewFriendBean.getEmail();
		
		userFriendsDAO.insert(userFriendsBean);
		try{
			
			

			try {
				Mail.postMail(  a, 
								"Friend Request", 
								"This is friend request from " + userBean.getFirst_name() + " " + userBean.getLast_name(), 
								"matrixapplication@gmail.com");
			} catch (MessagingException e) {
				e.printStackTrace();
			}
			
			
			request.setAttribute("friend_confirm", "<font color='green'>Friend request send</font>");
		
		
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("friend_confirm", "<font color='red'>You have sent friend request before</font>");
			
		}
		
		dispatcher.forward(request, response);
		
		
	}

}
